const helper = module.exports
const md5 = require('md5')
const shortid = require('shortid')
const Parameter = require('parameter')
const moment = require('moment')
const _ = require('lodash')

const parameter = new Parameter({
    validateRoot: true,
    widelyUndefined: true,
})

helper.uuid = (dna) => {
    return md5(`${helper.uuid_short()}${Math.random()}`) + (!!dna ? `_${dna}` : '')
}

helper.uuid_short = () => {
    return shortid.generate()
}

helper.now = (fmt) => {
    fmt = fmt || 'YYYY-MM-DD HH:mm:ss'
    return moment().format(fmt)
}

helper.md5 = (msg) => {
    return md5(msg)
}

helper.rdmFlowNo = () => {
    return this.now('YYYYMMDDHHmmss') + Math.floor(Math.random() * 100000)
}

helper.parse = (msg) => {
    return JSON.parse(JSON.stringify(msg))
}

helper.toTimeString = (time, fmt) => {
    if (!time) return ''

    fmt = fmt || 'YYYY-MM-DD HH:mm:ss'
    return moment(time).format(fmt)
}

helper.getQueryString = (name, search) => {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]')
    let regex = new RegExp('[\\?&]' + name + '=([^&#]*)')
    let results = regex.exec(search)
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '))
}

helper.isCellPhone = (n) => {
    return /^1\d{10}$/.test(n)
}

helper.isEmail = (n) => {
    return /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(n)
}

helper.isPrice = (n) => {
    return /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(n)
}

// 添加校验价格规则
parameter.addRule('arrayOrObject', (rule, value) => {
    if (!_.isObject(value)) {
        return 'should be an array or object'
    }
})

// 添加校验手机号规则
parameter.addRule('mobile', (rule, value) => {        // value就是待检验的数据
    if (!/^1\d{10}$/.test(value)) {
        return 'should be an mobile'
    }
})

// 添加校验邮箱规则
parameter.addRule('email', (rule, value) => {        // value就是待检验的数据
    if (!/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(value)) {
        return 'should be an email'
    }
})

// 添加校验价格规则
parameter.addRule('price', (rule, value) => {        // value就是待检验的数据
    if (!/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(value)) {
        return 'should be an price'
    }
})

helper.validate = (rule, data = {}) => {
    let result = parameter.validate(rule, data)
    if (_.isArray(result) && result.length > 0) {
        throw new Error(`${_.get(result, '0.field')} ${_.get(result, '0.message')}`)
    }
    return true
}

helper.parseParams = (params) => {
    if (!_.isObject(params)) return params
    let now = helper.now()

    if (_.isArray(params)) {
        params.forEach(_p => {
            Object.keys(_p).map(m => {
                _p[m] = _p[m].replace(/\$id/gi, helper.uuid())
                    .replace(/\$shortid/gi, helper.uuid_short())
                    .replace(/\$now/gi, now)
            })
        })
    } else {
        Object.keys(params).map(m => {
            params[m] = params[m].replace(/\$id/gi, helper.uuid())
                .replace(/\$shortid/gi, helper.uuid_short())
                .replace(/\$now/gi, now)
        })
    }

    return params
}
